﻿using Microsoft.OpenApi.Models;

using Swashbuckle.AspNetCore.SwaggerGen;

using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;

namespace WXWorkSvc.Common.Models;
public class SwaggerSchemaFilter : ISchemaFilter
{
    public void Apply(OpenApiSchema schema, SchemaFilterContext context)
    {
        if (context.Type == null)
            return;
        

        if (context.Type.IsEnum)
        {

            List<string> titleItems = new List<string>();

            foreach (var e in Enum.GetValues(context.Type))
            {
                var desc = context.Type.GetField(e.ToString()!)!.GetCustomAttribute<DescriptionAttribute>();
                titleItems.Add($"{(int)e}：{desc?.Description ?? e}");
            }
            
            schema.Description = string.Join("；", titleItems);
        }
        else if (context.MemberInfo != null)
        {

            if (schema.Description == null)
            {
                var display = context.MemberInfo.GetCustomAttribute<DisplayAttribute>();
                if (display is null)
                    schema.Description = context.MemberInfo.GetCustomAttribute<DisplayNameAttribute>()?.DisplayName;
                else
                    schema.Description = string.IsNullOrEmpty(display.Description) ? display.Name : $"${display.Name}({display.Description})";
            }
            //if (context.MemberInfo?.Name == "ContactName")
            //{
            //    var t = // != null;
            //    schema.Description = "abc;";
            //    schema.Nullable = true;
            //}
            //else
            schema.Nullable = context.Type.Name.StartsWith("Nullable") || context.MemberInfo.GetCustomAttribute<DisplayAttribute>()?.GetOrder() == -1;

            //if (context.Type == typeof(string))
            //    schema.Nullable = context.Type.GetCustomAttribute<AllowNullAttribute>() != null;
            //else
            //    schema.Nullable = context.Type.Name.StartsWith("Nullable");

        }
    }
}
